#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <cassert>

using namespace std;

void handler(int signo)
{
    cout << "我是一个进程，刚刚获取了一个信号: " << signo << endl;
}

void FreeChild(int signo)
{
    assert(signo == SIGCHLD);
    while (true)
    {
        pid_t id = waitpid(-1, nullptr, WNOHANG);

        if (id > 0)
        {
            cout << "父进程等待成功, child pid: " << id << endl;
        }
        else if (id == 0)
        {
            // 还有子进程，但是现在没退出
            cout << "还有子进程，但是现在还没退出，父进程要去做自己的事情了" << endl;
            break;
        }
        else
        {
            cout << "父进程等待所有子进程结束" << endl;
            break;
        }
    }
}

int main()
{
    signal(SIGCHLD, FreeChild);
    for (int i = 0; i < 10; ++i)
    {
        pid_t id = fork();
        if (id == 0)
        {
            int cnt = 0;

            if (i < 7)
                cnt = 5;
            else
                cnt = 10;

            while (cnt)
            {
                cout << "我是子进程, pid: " << getpid() << " 当前的cnt: " << cnt-- << endl;
                sleep(1);
            }
            cout << "子进程退出，进入僵尸状态" << endl;
            exit(0);
        }
    }

    while (true)
    {
        cout << "我是父进程，我正在运行: " << getpid() << endl;
        sleep(1);
    }

    return 0;
}